package com.dongbing.support.loader;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.GlobalConfigUtils;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.dongbing.entity.base.BaseEntity;
import com.dongbing.enums.BatchTaskBizType;
import com.dongbing.support.CollectBeanPostProcessor;
import com.sun.istack.internal.NotNull;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.SqlSessionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 批量任务数据加载机
 * @param <T> 实体类
 * @param <R> 请求参数
 */
public abstract class BatchTaskDataLoader<T extends BaseEntity, R> {

    /**
     * 构建数据查询语句
     * @param request 请求参数
     * @return req
     */
    public abstract LambdaQueryWrapper<T> buildQueryWrapper(R request);

    /**
     * 批量任务类型(定位执行器)
     * @return 批量任务执行类型
     */
    public abstract BatchTaskBizType type();

    /**
     * 批量任务执行实体类类型
     * @return Class
     */
    public abstract Class<T> entityClass();

    /**
     * 丰富数据
     * @param list 实体类对象集合 只有Id一个参数
     * @return res
     */
    public List<T> enrichData(List<T> list) {
        // 获取mybatis-plus表结构
        TableInfo tableInfo = TableInfoHelper.getTableInfo(entityClass());
        // 将查询的id全部查询出来
        List<Long> idLists = list.stream().map(BaseEntity::getId).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(idLists)) {
            QueryWrapper<T> queryWrapper = new QueryWrapper<>();
            queryWrapper.in(tableInfo.getKeyColumn(), idLists);
            return this.load(queryWrapper);
        } else {
            return new ArrayList<>();
        }
    }

    /**
     * 加载数据
     * @param queryWrapper 组装条件
     * @return 查询数据
     */
    public List<T> load(@NotNull Wrapper<T> queryWrapper) {
        SqlSession sqlSession = null;
        Class<T> modelClass = entityClass();
        try {
            sqlSession = SqlHelper.sqlSession(modelClass);
            BaseMapper<T> baseMapper = SqlHelper.getMapper(modelClass, sqlSession);
            return baseMapper.selectList(queryWrapper);
        } finally {
            if (Objects.nonNull(sqlSession)) {
                SqlSessionUtils.closeSqlSession(sqlSession, GlobalConfigUtils.currentSessionFactory(modelClass));
            }
        }
    }

}
